
//控制loading是因为有时一个页面会请求多个接口，出现多个loading体验不是很好

function get(url, params, onSuccess, loadding = true){
  request(url, params, "GET", onSuccess, loadding);
}

function post(url, params, onSuccess, loadding = true){
  request(url, params, "POST", onSuccess, loadding);
}

function request(url, params = {}, method = 'GET', onSuccess, loadding = true) {
  if (loadding==true) {
      wx.showLoading({
          title: "加载中..."
      })
  };
  wx.request({
      url: get_url(url),
      data: params,
      method: method,
      header: {
          'content-type': 'application/json',
          'accesstoken' : wx.getStorageSync('token')
      },
      success: function(res) {
        if (res.data) {
            if (res.statusCode == 200) {
                onSuccess(res.data);
            } else {
                console.log(res);
                wx.showToast({
                    title: '请求失败',
                    icon: 'none',
                    duration: 3000
                });
            }
        }
        if (loadding==true) {
            wx.hideLoading();
        }
      },
      fail: function(error) {
          console.log(error);
          wx.showToast({
              title: error.errMsg,
              icon: 'none',
              duration: 3000
          });
      }
  })
}

function get_url(url) {
  var base_url = "接口请求地址";
  return base_url + url;
}

//提供给外部使用
module.exports = {
  post: post,
  get: get,
}